/*
 * Copyright (C) Antonio Ramon Morcillo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package soft.xitxarello.su.fragments;

import java.util.List;
import java.util.ListIterator;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.widget.Button;
import org.holoeverywhere.widget.LinearLayout;
import org.holoeverywhere.widget.TextView;

import soft.xitxarello.su.R;
import soft.xitxarello.su.data.App;
import soft.xitxarello.su.data.PermsGroup;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

/**
 * A fragment that displays one uninstallable application.
 * 
 * @see org.holoeverywhere.app.Fragment
 */
public class DetailFragment extends Fragment {

    // Logging tag
    private final String TAG = "seasonsend";

    // Flag for uninstall action result
    public static final int REQUEST_UNINSTALL = 1;

    /**
     * Create a new instance of DetailFragment.
     */
    public static DetailFragment newInstance(App app) {
        DetailFragment f = new DetailFragment();

        // Supply app input as an argument.
        Bundle args = new Bundle();
        args.putParcelable("app", app);
        f.setArguments(args);

        return f;
    }

    /**
     * Getter Method.
     * 
     * @return uninstallable application as App.
     */
    public App getApp() {
        return getArguments().getParcelable("app");
    }

    /**
     * Overrides a superclass method. Called to have the fragment instantiate
     * its user interface view.
     * 
     * @param inflater The LayoutInflater object that can be used to inflate any
     *            views in the fragment.
     * @param container If non-null, this is the parent view that the fragment's
     *            UI should be attached to. The fragment should not add the view
     *            itself, but this can be used to generate the LayoutParams of
     *            the view.
     * @param savedInstanceState If non-null, this fragment is being
     *            re-constructed from a previous saved state as given here.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // inflate /res/layout/detail_item.xml resource.
        View view = inflater.inflate(R.layout.detail_item, container, false);

        ((ImageView) view.findViewById(R.id.app_icon_detail)).setImageDrawable(getApp()
                .getIcon(getActivity()));
        ((TextView) view.findViewById(R.id.app_name_detail))
                .setText(getApp().getName(getActivity()));
        ((TextView) view.findViewById(R.id.app_version_detail)).setText(getActivity()
                .getString(R.string.app_version) + " " + getApp().getVersion(getActivity()));
        ((TextView) view.findViewById(R.id.description_text)).setText(getApp().getDescription(
                getActivity()));

        // Get Application Group Permissions as a list and create an iterator.
        List<PermsGroup> groups = getApp().getPermissions(getActivity());
        ListIterator<PermsGroup> groupsIterator = groups.listIterator();

        // Get LinearLaout view
        LinearLayout layout = (LinearLayout) view.findViewById(R.id.permissions);

        // No permissions found.
        if (groups.isEmpty()) {
            LinearLayout permissionsBlockLayout = (LinearLayout) view
                    .findViewById(R.id.detail_permissions_block);
            permissionsBlockLayout.setVisibility(View.GONE);
        }

        // Add all permissions to the ui.
        while (groupsIterator.hasNext()) {
            // New TextView for Permissions Group.
            TextView tvGroup = new TextView(getActivity());
            tvGroup.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            String tmpGroupName = (String) groupsIterator.next().getGroupName();
            tvGroup.setText(tmpGroupName);
            tvGroup.setTypeface(null, Typeface.BOLD);
            tvGroup.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_go_search_api_holo_light,
                    0, 0, 0);
            tvGroup.setId(groupsIterator.nextIndex());
            // Add View to the GroupView.
            ((LinearLayout) layout).addView(tvGroup);
        }

        return view;
    }

    /**
     * Overrides a superclass method. Called when the fragment's activity has
     * been created and this fragment's view hierarchy instantiated.
     * 
     * @param Bundle savedInstanceState
     * @see android.os.Bundle
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Set a Listener to the open button.
        setOpenButtonAction();

        // Set a Listener to the uninstall button.
        setUninstallButtonAction();

        // Set a Listener to the google play link.
        setGooglePlayLinkAction();

    }

    /**
     * Set a Listener and an action to the open button.
     */
    private void setOpenButtonAction() {

        final Button bt = (Button) getActivity().findViewById(R.id.open_button);

        try {
            PackageManager pm = getActivity().getPackageManager();
            Intent launchIntent = pm.getLaunchIntentForPackage(getApp().getPackageName());
            if (launchIntent == null) {
                bt.setEnabled(false);
                return;
            }

        } catch (NullPointerException e) {
            bt.setEnabled(false);
            Log.e(TAG, "NullPointerException " + e.getMessage());
            Log.e(TAG, e.toString());
        }

        bt.setOnClickListener(new OnClickListener() {

            /**
             * Overrides a superclass method. Called when a view has been
             * clicked.
             * 
             * @param v The view that was clicked.
             */
            @Override
            public void onClick(View v) {
                try {
                    PackageManager pm = getActivity().getPackageManager();
                    Intent launchIntent = pm.getLaunchIntentForPackage(getApp().getPackageName());
                    startActivity(launchIntent);
                } catch (NullPointerException e) {
                    bt.setEnabled(false);
                    Log.e(TAG, "NullPointerException " + e.getMessage());
                    Log.e(TAG, e.toString());
                }
            }

        });
    }

    /**
     * Set a Listener and an action to the uninstall button.
     */
    private void setUninstallButtonAction() {

        final Button bt = (Button) getActivity().findViewById(R.id.uninstall_button);

        bt.setOnClickListener(new OnClickListener() {

            /**
             * Overrides a superclass method. Called when a view has been
             * clicked.
             * 
             * @param v The view that was clicked.
             */
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:"
                            + getApp().getPackageName()));
                    intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
                    getActivity().startActivityForResult(intent, REQUEST_UNINSTALL);
                } catch (ActivityNotFoundException e) {
                    bt.setEnabled(false);
                    Log.e(TAG, "ActivityNotFoundException " + e.getMessage());
                    Log.e(TAG, e.toString());
                }
            }

        });
    }

    /**
     * Set a Listener and an action to the google play link.
     */
    private void setGooglePlayLinkAction() {

        TextView tvPlay = (TextView) getActivity().findViewById(R.id.google_play_link_tv);

        tvPlay.setOnClickListener(new OnClickListener() {

            /**
             * Overrides a superclass method. Called when a view has been
             * clicked.
             * 
             * @param v The view that was clicked.
             */
            @Override
            public void onClick(View v) {
                try {
                    Intent playIntent = new Intent(Intent.ACTION_VIEW);
                    playIntent.setData(Uri
                            .parse("market://details?id=" + getApp().getPackageName()));
                    playIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    startActivity(playIntent);
                } catch (ActivityNotFoundException e) {
                    Log.e(TAG, "ActivityNotFoundException " + e.getMessage());
                    Log.e(TAG, e.toString());
                }
            }

        });
    }
}
